<?php

namespace App\Containers\AppSection\Qualification\UI\API\Transformers;

use App\Containers\AppSection\File\Models\File;
use App\Containers\AppSection\File\UI\API\Transformers\FileTransformer;
use App\Containers\AppSection\Profile\UI\API\Transformers\ProfileTransformer;
use App\Containers\AppSection\Qualification\Models\Qualification;
use App\Containers\AppSection\Status\UI\API\Transformers\StatusTransformer;
use App\Ship\Parents\Transformers\Transformer;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;

class QualificationTransformer extends Transformer
{
    protected array $defaultIncludes = [
        'remarks', 'status'
    ];

    /**
     * @var  array
     */
    protected array $availableIncludes = [
        'moderator', 'profile'
    ];

    public function transform(Qualification $t): array
    {
        $response = [
            'object' => $t->getResourceKey(),
            'include' => $this->getAvailableIncludes(),
            'id' => $t->getHashedKey(),
            'stage' => $t->stage,
            'remarks' => $t->remarks,
            'conditions' => $t->conditions,
            'remark' => $t->remark,
            'qualified_at' => $this->dateFormatter($t->qualified_at),
            'unqualified_at' => $this->dateFormatter($t->unqualified_at),
            'created_at' => $this->dateFormatter($t->created_at),
            'updated_at' => $this->dateFormatter($t->updated_at),
            'readable_created_at' => $t->created_at->diffForHumans(),
            'readable_updated_at' => $t->updated_at->diffForHumans()];

        foreach ($t->conditions['conditions'] as $key => $condition) {
            if (isset($condition['type']) && $condition['type'] === 'files') {
                foreach ($condition['items'] as $key2 => $item) {
                    if (!empty($item['files'])) {
                        $files = $this->collection(File::whereIn('id', (array)$item['files'])->get() ?? [], new FileTransformer)->getData();
                        $response['conditions']['conditions'][$key]['items'][$key2]['files'] = $files;
                    }
                }
            }
        }

        return $response;
    }

    public function includeProfile(Qualification $t): Item
    {
        return $this->item($t->profile, new ProfileTransformer);
    }

    public function includeModerator(Qualification $t): ?Item
    {
        return $this->nullableItem($t->moderator, new ProfileTransformer);
    }

    public function includeRemarks(Qualification $t): Collection
    {
        return $this->collection($t->remarks, new RemarkTransformer);
    }

    public function includeStatus(Qualification $t): ?Item
    {
        return $this->nullableItem($t->status, new StatusTransformer);
    }
}
